import pickle
import demjson
import time
import random
import urllib3
import logging
import os
import sqlite3
import sys
from selenium import webdriver
from aip import AipOcr
from selenium.webdriver.common.action_chains import ActionChains

logging.basicConfig(filename="xf.log",filemode="a",level=logging.INFO,format='%(asctime)s -%(levelname)s -%(process)d -%(module)s -%(funcName)s -%(message)s')

#userAccount='15368274761'
#userPassword="af1121113"
#loginUserAccount='5306211470018'
userAccount='5306011240109'
userPassword="yxm643200"
loginUserAccount='5306011240109'
url='http://xf.faxuan.net/bps/frame/t/frame.html?loginUserAccount=%s'%(loginUserAccount)
""" 你的 APPID AK SK """
APP_ID = '11243469'
API_KEY = 'LkbGHrd9BVGtQBvMpZLCG225'
SECRET_KEY = 'Hs7z1TfNeVQFr4QOqfi69vpkXsUIO81Q'

tryTime=20

client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
browser = webdriver.Chrome()
browser.implicitly_wait(10)
http = urllib3.PoolManager()
db = sqlite3.connect(os.path.dirname(__file__) + "/test.db")
cur = db.cursor()

def loadCookie():
    try:
        cookieFile=open(os.path.dirname(__file__)+"/cookie.log","rb")
        cookdict=pickle.loads(cookieFile.read())
        for val in cookdict:
            logging.info({'name': val['name'], 'value': val['value']})
            browser.add_cookie({'name': val['name'], 'value': val['value']})
        cookieFile.close()
    except:
        return False


def saveCookie():
    cookieDict=browser.get_cookies()
    cookieFile=open(os.path.dirname(__file__)+"/cookie.log","wb")
    logging.debug(cookieDict)
    cookieFile.write(pickle.dumps(cookieDict))
    cookieFile.close()


def cookieLogin():
    logging.info(browser.title)
    loadCookie()
    browser.get(url)
    logging.info(browser.title)
    if(browser.title == '法宣在线'):
        return True
    else:
        inname=browser.find_element_by_id('userAccount')
        inpwd= browser.find_element_by_id('userPassword')
        inname.clear()
        inpwd.clear()
        inname.send_keys(userAccount)
        inpwd.send_keys(userPassword)
        return False

def login():
    global tryTime
    inname=browser.find_element_by_id('userAccount')
    inpwd= browser.find_element_by_id('userPassword')
    incheckcode = browser.find_element_by_id('usercheckcode')
    for i in range(tryTime):
        inname.clear()
        inpwd.clear()
        incheckcode.clear()
        inname.send_keys(userAccount)
        inpwd.send_keys(userPassword)
        code=getCheckCode()
        while len(code)!=4:
            code=getCheckCode()
        incheckcode.send_keys(code)
        browser.execute_script('bps.userloginAction()')
        time.sleep(1)#id popwinContent
        try:
            closepopwin=browser.find_element_by_id('popwinConfirm')
        except:
            return True
        else:
            actions = ActionChains(browser)
            actions.move_to_element(closepopwin)
            actions.click(closepopwin)
            actions.perform()
    logging.warning("login error!")
    sys.exit(0)

def getCookiesStr():
    cookie = [item["name"] + "=" + item["value"] for item in browser.get_cookies()]
    cookiestr = ';'.join(item for item in cookie)
    return cookiestr

def getCheckCode():
    http = urllib3.PoolManager()
    r=http.request(
        'GET',
        'http://xf.faxuan.net/service/gc.html?timestamp='+str(int(time.time())*1000),
        headers={'Cookie':getCookiesStr()}
        )
    img=r.data
    f=open(os.path.dirname(__file__)+"\\temp.jpg","wb")
    f.write(img)
    f.close()
    #im=Image.load(img)
    #im.show()
    options = {}
    options["language_type"] = "ENG"
    options["probability"] = "true"
    checkcodeinfo=client.basicGeneral(img,options)
    error_info=checkcodeinfo.get('error_msg')
    if(error_info!=None):
        logging.error(error_info)
        sys.exit(1)
    codestr=checkcodeinfo['words_result'][0]['words']
    logging.info(codestr)
    return codestr.replace(' ', '')

def getAnswerJson(p,s):
    url="http://xf.faxuan.net/ess/service/getpaper?paperId=%s&series=%s_answer"%(p,s)
    logging.info(url)
    r = http.request(
        'GET',
        url
    )
    da = r.data
    da=da.decode("utf-8")
    das=da.split("\r\n")
    logging.info("read xhr data:%s"%(da))
    if(len(das) <3 ):
        logging.warning("xhr read error!")
        return None
    else:
        try:
            getjson = demjson.decode(das[2])
        except:
            logging.warning("json解析错误")
            return None
        else:
            return getjson

def sqlAnswerInsert(obj):
    if(obj == None):
        logging.warning("数据有误")
        return False
    for d in obj:

        result=cur.execute("SELECT * FROM xf WHERE id= %s "%(d['questionId']))
        row=result.fetchone()
        if(row==None):
            cur.execute("INSERT INTO xf (id,answerNo) VALUES (%s,'%s')"%(d['questionId'],d['answerNo']))
            db.commit()
            logging.info("INSERT id:%s ; answerNo:%s"%(d['questionId'],d['answerNo']))
        elif (row[4]=="" or row[4]==None):
            cur.execute("UPDATE xf SET answerNo='%s' WHERE (id=%s)" % (d['answerNo'],d['questionId']))
            db.commit()
            logging.info("UPDATE id:%s ; answerNo:%s" % (d['questionId'], d['answerNo']))
        elif(row[4] != d['answerNo'] ):
            logging.error("answerNo conflict!")

def page(index):
    while True:
        try:
            browser.execute_script("base.index2(%s)"%(index))
        except:
            logging.info("javascript 没有加载完")
            time.sleep(3)
        else:
            time.sleep(5)
            return True

def openJobPage():
    if (browser.title != "课程列表"):
        page('1')
    while True:
        time.sleep(3)
        logging.info("in while")
        try:
            lis = browser.find_elements_by_xpath("//ul[@id='page']/li/a/div/img")
        except:
            logging.info("not find page list")
        else:
            if (len(lis) >= 1):
                s = random.randint(0, len(lis) - 1)
                logging.info(s)
                print(browser.execute_script('return $("#page").find("img").length'))
                browser.execute_script('$("#page").find("img")[%d].click()' % (s))
                break

def swithcNew(index):
    time.sleep(1)
    global mainpage
    all_handles = browser.window_handles
    if(len(all_handles)>index):
        browser.switch_to.window(all_handles[index])  # 切换到新页面
        logging.info("now page:%s"%(all_handles[index]))
        return True
    else:
        logging.warning("没有这个页面")
        return False

def tryjs(js):
    while True:
        try:
            logging.info(js)
            r=browser.execute_script(js)
        except:
            logging.info("javascript 没有加载完")
            time.sleep(3)
        else:
            return r

def doWork():
    swithcNew(1)
    tryjs('sps.exitStudy()') #打开练习页
    browser.execute_script("$('.coursetab.clear').find('li')[2].click()")
    js=browser.execute_script('return $("#lx-box-id").find("a").attr("href")')
    browser.execute_script(js)
    swithcNew(2)
    hid=tryjs("return $('#hid').val()")
    hids = tryjs("return $('#hids').val()")
    print(hid)
    print(hids)

    cookieDict = browser.get_cookies()
    for v in cookieDict:
        if(v['name'] == 'ex_range_'+hid):
            print("qweewq:",v['value'])
            answerobj=getAnswerJson(hid,v['value'])
            sqlAnswerInsert(answerobj)
    selectAnswer(answerobj)
    tryjs("sps.myCommit()")
    time.sleep(1)
    tryjs("$('#popwinConfirm').click()")
    time.sleep(10)
    browser.close()
    swithcNew(1)
    time.sleep(2)
    tryjs("$('#popwinConfirm').click()")
    swithcNew(0)

def uptime():
    time.sleep(1)
    mainpage = browser.current_window_handle
    all_handles = browser.window_handles
    for handle in all_handles:  # 遍历全部页面句柄
        if handle != mainpage:  # 判断条件
            browser.switch_to.window(handle)  # 切换到新页面
    browser.execute_script("sessionStorage.timecur=Date.now() - %d" % (random.randint(600000,900000)))
    time.sleep(1)
    browser.execute_script('location.reload()')
    while True:
        objl=tryjs("return $('#kejmc-box-id').find('a').length")
        logging.info("<a>:%s"%(objl))
        if(objl >=1 ):
            break
        else:
            time.sleep(3)
    time.sleep(3)
    tryjs("$('#kejmc-box-id').find('a')[0].click()")
    while True:
        try:
            time.sleep(5)
            browser.execute_script('sps.exitStudy(\'ware_time_num\')')
        except:
            logging.info("javascript 没有加载完")
            time.sleep(3)
        else:
            time.sleep(3)
            browser.execute_script("$('#popwinConfirm').click()")
            break
    browser.switch_to.window(mainpage)

def selectAnswer(answerobj):
    for v in range(0,len(answerobj)):
        tryjs("sps.changeWenTi(%d)" % (v))
        time.sleep(1)
        l=int(tryjs("return $('#ti_item').find('input').length"))
        ans = answerobj[v]["answerNo"]
        print("answerNo:",ans,type(ans))
        for n in range(0,l):
            op=tryjs("return $('#ti_item').find('input')[%d].value"%(n))
            print(op)
            if(ans.find(op) != -1):
                tryjs("$('#ti_item').find('input')[%d].click()"%(n))

        if(ans=='1'):
            tryjs("$('#ti_item').find('input')[0].click()")
        elif(ans=='0'):
            tryjs("$('#ti_item').find('input')[1].click()")

def getpoint():
    url="http://xf.faxuan.net/useris/service/getdetail?userAccount=%s&key=Sun+May+20+2018+19%3A09%3A39+GMT%2B0800"%(loginUserAccount)
    r = http.request(
        'GET',
        url
    )
    da = r.data

logging.info("START")
browser.get('http://xf.faxuan.net/')
'''
if(cookieLogin()):
    logging.info("cookie 失效")
else:
    login()
    '''
login()
browser.get(url)
try:
    db.execute("CREATE TABLE 'xf' ('id'  INTEGER NOT NULL,'content'  TEXT,'options'  TEXT,'type'  INTEGER,'answerNo'  TEXT,PRIMARY KEY ('id'));")
except:
    logging.debug("db already exists")
else:
    db.commit()
openJobPage() #打开学习页面
uptime() #更新学习时间


openJobPage() #打开学习页面
doWork()
openJobPage() #打开学习页面
doWork() #
time.sleep(3)

saveCookie()
db.close()
logging.info("END")
browser.quit()


